<template>
  <!-- tab基本信息表单  -->
  <div id="BacIntelligentExpertRuleForm">
    <Splitpanes class="area" horizontal>
      <Pane size="65">
        <el-scrollbar style="height:100%;">
          <vxe-table ref="tableRef" border="inner" align="left" class="mytable-scrollbar" :data="conditionList" @cell-dblclick="showDataDialog" :row-config="{ isCurrent: true, isHover: true }" :column-config="{ resizable: true }" :edit-config="{ trigger: 'click', mode: 'cell', showStatus: true }" show-overflow keep-source>
            <vxe-column type="seq" width="60"></vxe-column>
            <vxe-column field="conditionName" title="条件类型" width="120">
            </vxe-column>
            <vxe-column field="meetWith" title="满足" width="120px">
              <template #default="{ row }">
                <img style="width:16px;height:16px;margin-top:5px;" v-if="row.meetWith" :src="`${getAssetsFile('isCheck.png')}`" />
                <img style="width:16px;height:16px;margin-top:5px;" v-if="!row.meetWith&&row.conditionValue" :src="`${getAssetsFile('noCheck.png')}`" />
              </template>
            </vxe-column>
            <vxe-column field="conditionValueLabel" title="取值（双击开窗）" align="center">
            </vxe-column>
          </vxe-table>
          <vxe-form ref="formRef" :data="formData" span="24" title-align="right" title-width="70" style="margin-top:10px;">
            <vxe-form-item title="其他项目(双击开窗)" field="ruleCode">
              <template #default="{ data }">
                <vxe-textarea @dblclick="openOtherItem" v-model="data.otherItem" placeholder="" readonly resize="vertical" :autosize="{ minRows: 2, maxRows: 8 }"></vxe-textarea>
              </template>
            </vxe-form-item>
            <vxe-form-item title="抗生素规则(双击开窗)" field="ruleCode">
              <template #default="{ data }">
                <vxe-textarea @dblclick="openAntibiotic" v-model="data.antibioticRule" placeholder="" readonly resize="vertical" :autosize="{ minRows: 2, maxRows: 8 }"></vxe-textarea>
              </template>
            </vxe-form-item>

          </vxe-form>
        </el-scrollbar>
      </Pane>
      <Pane size="35">
        <vxe-button status="primary" @click="addOperat" content="新增明细"></vxe-button>
        <vxe-button mode="text" @click="deleteOperat" status="danger" content="删除明细"></vxe-button>
        <vxe-table ref="OperatTableRef" border="inner" align="left" class="mytable-scrollbar" height="auto" :data="operatList" :row-config="{ isCurrent: true, isHover: true }" :column-config="{ resizable: true }" :edit-config="{ trigger: 'click', mode: 'cell' }" show-overflow keep-source>
          <vxe-column field="effect" title="有效" width="80">
            <template #default="{ row }">
              <vxe-checkbox v-model="row.effect" size="medium"></vxe-checkbox>
            </template>
          </vxe-column>
          <vxe-column field="operatRule" title="操作规则" width="120px" :edit-render="{}">
            <template #default="{ row }">
              <span>{{ formatCommon(operatOptions, row.operatRule) }}</span>
            </template>
            <template #edit="{ row }">
              <vxe-select v-model="row.operatRule" transfer>
                <vxe-option v-for="item in operatOptions" :key="item.value" :value="item.value" :label="item.name"></vxe-option>
              </vxe-select>
            </template>
          </vxe-column>
          <vxe-column field="operatContent" title="操作内容" :edit-render="{}">
            <template #edit="{ row }">
              <vxe-input v-model="row.operatContent"></vxe-input>
            </template>
          </vxe-column>
        </vxe-table>
      </Pane>
      <!-- 配置扩展属性弹框 -->
      <!-- <EditExtraProperties ref="EditExtraPropertiesRef" /> -->
    </Splitpanes>

    <vxe-modal v-model="showDataSelectDialog" :title="dialogTitle" width="70vw" height="70vh" :mask="false" :lock-view="false" resize>
      <Splitpanes class="area">
        <Pane size="50">
          <vxe-toolbar perfect>
            <template #buttons>
              <vxe-input v-model="dialogForm.keyvalue" type="search" clearable class="vxeInputSearch" placeholder="关键字查询"></vxe-input>
              <vxe-button style="margin-left:10px;" type="text" class="button-blue" icon="vxe-icon-refresh" content="刷新"></vxe-button>
            </template>
          </vxe-toolbar>
          <el-scrollbar style="height:100%;">
            <vxe-table ref="tableRef" border align="left" class="mytable-scrollbar" height="500" :data="dialogForm.dataList" @cell-dblclick="addUseDataList" :row-config="{ isCurrent: true, isHover: true }" :column-config="{ resizable: true }" show-overflow keep-source>
              <vxe-column type="seq" title="#" width="30"></vxe-column>
              <vxe-column field="code" title="代码" width="120">
              </vxe-column>
              <vxe-column field="name" title="名称" width="120">
              </vxe-column>
              <vxe-column field="inputCode" title="输入码" align="center">
              </vxe-column>
            </vxe-table>
          </el-scrollbar>
        </Pane>
        <Pane size="50">
          <vxe-toolbar perfect>
            <template #buttons>
              <vxe-radio-group v-model="dialogForm.condition">
                <vxe-radio :label="1" content="满足"></vxe-radio>
                <vxe-radio :label="2" content="除外"></vxe-radio>
              </vxe-radio-group>
              <vxe-button style="margin-left:50px;" type="text" class="button-blue" icon="vxe-icon-save" content="确定" @click="confirmDialog"></vxe-button>
            </template>
          </vxe-toolbar>
          <vxe-table ref="tableRef" border align="left" class="mytable-scrollbar" height="500" :data="dialogForm.useDataList" @cell-dblclick="cancleUseDataList" :row-config="{ isCurrent: true, isHover: true }" :column-config="{ resizable: true }" show-overflow keep-source>
            <vxe-column type="seq" title="#" width="30"></vxe-column>
            <vxe-column field="code" title="代码" width="120">
            </vxe-column>
            <vxe-column field="name" title="名称" width="120">
            </vxe-column>
            <vxe-column field="inputCode" title="输入码" align="center">
            </vxe-column>
          </vxe-table>
        </Pane>
        <!-- 配置扩展属性弹框 -->
        <!-- <EditExtraProperties ref="EditExtraPropertiesRef" /> -->
      </Splitpanes>

    </vxe-modal>

    <vxe-modal v-model="showBacItemDialog" title="其他条件向导" width="55vw" height="70vh" :mask="false" :lock-view="false" resize>
      <BacIntelligentItem ref="refBacIntelligentItem" @addItemRules="addItemRules" @closeItemRules="closeItemRules"></BacIntelligentItem>
    </vxe-modal>

    <vxe-modal v-model="showBacAntibioticDialog" title="抗生素规则" width="60vw" height="70vh" :mask="false" :lock-view="false" resize>
      <BacIntelligentAntibiotic ref="refBacIntelligentAntibiotic" @addAntibioticRules="addAntibioticRules" @closeAntibioticRules="closeAntibioticRules"></BacIntelligentAntibiotic>
    </vxe-modal>

    <vxe-modal v-model="showBacConditionAgeRef" title="年龄" width="30vw" height="40vh" :mask="false" :lock-view="false" resize>
      <vxe-button content="新增" type="text" class="button-blue" icon="vxe-icon-add" @click="BacConditionAgeAdd"> </vxe-button>
      <vxe-button content="保存" type="text" style="margin-left:10px;" class="button-blue" icon="vxe-icon-save" @click="BacConditionAgeSave"> </vxe-button>
      <vxe-table ref="refParamCompare" border resizable show-overflow :data="BacConditionAgeList" :edit-config="{ trigger: 'click', mode: 'cell' }">
        <vxe-column type="seq" width="60"></vxe-column>
        <vxe-column field="startAge" title="起始年龄(岁)>=" :edit-render="{ autofocus: '.vxe-input--inner' }">
          <template #edit="{ row }">
            <vxe-input v-model="row.startAge" type="text"></vxe-input>
          </template>
        </vxe-column>
        <vxe-column field="endAge" title="结束年龄(岁)<=" :edit-render="{}">
          <template #edit="{ row }">
            <vxe-input v-model="row.endAge" type="text" placeholder="请输入昵称"></vxe-input>
          </template>
        </vxe-column>
        <vxe-column title="操作" align="center">
          <template #default="{ rowIndex }">
            <vxe-button type="text" status="danger" icon="vxe-icon-delete" circle @click="BacConditionAgeDelte(rowIndex)"> </vxe-button>
          </template>
        </vxe-column>
      </vxe-table>
    </vxe-modal>
  </div>
</template>

<script lang="ts" setup>
// 引入组件区 ==========
import { ref, reactive, watch, getCurrentInstance, PropType, onMounted } from 'vue';
import { VXETable, VxeFormPropTypes, VxeButtonEvents } from 'vxe-table';
import { VxeMessage, VxeNotifyType } from '../../../utils/CommonMessage';
import { funBdsJsResult } from '../../../utils/Expression'; //函数公式
import VxePulldownSelection from '../../../components/VxePulldownSelection.vue'; //引用下拉框组件
import EditExtraProperties from '../../../components/EditExtraProperties.vue'; //配置扩展属性弹框组件
import SelectDataList from '../../../components/SelectDataList.vue';
import { Splitpanes, Pane } from 'splitpanes';
import VxePulldownMultiSelection from '@/components/VxePulldownMultiSelection.vue';
import BacIntelligentItem from './BacIntelligentItem.vue';
import BacIntelligentAntibiotic from './BacIntelligentAntibiotic.vue';
import { getAssetsFile } from '../../../utils/common'; //notifyType, notifyMessage,

// 全局变量定义区 ==========
let { proxy }: any = getCurrentInstance();
let sourcelist = reactive([]);
let orderNum = ref(null);
let index = ref(null);
let tableRef = ref(null);
let OperatTableRef = ref(null);
let formData = reactive({});
let conditionList = reactive([]);
let operatList = reactive([]);
let showDataSelectDialog = ref(false);
let showBacItemDialog = ref(false);
let showBacAntibioticDialog = ref(false);
let dialogTitle = ref('');
let keyvalue = ref(null);
let currentRow = reactive({});
let currentConditionRow: any = reactive({});
let refBacIntelligentItem = ref(null);
let refBacIntelligentAntibiotic = ref(null);
let showBacConditionAgeRef = ref(null);
let BacConditionAgeList = reactive([]);
let dialogForm = reactive({
  keyvalue: '',
  condition: null,
  dataList: [],
  useDataList: []
});

let operatOptions = [
  {
    name: '禁止审核',
    value: '1'
  },
  {
    name: '生成危急值',
    value: '2'
  }
];

// 表单校验规则

const EditExtraPropertiesRef = ref(null); //配置扩展属性弹框ref
// const collapseStatus = ref(false);

defineExpose({
  getRowList,
  saveAllBacRule
});

async function BacConditionAgeAdd(): Promise<void> {
  const record = {
    startAge: '',
    endAge: ''
  };
  BacConditionAgeList.push(record);
}

function BacConditionAgeDelte(index) {
  BacConditionAgeList.splice(index, 1);
}

async function BacConditionAgeSave() {
  if (BacConditionAgeList && BacConditionAgeList.length > 0) {
    let datas = [];
    BacConditionAgeList.forEach((item) => {
      datas.push(item.startAge + '-' + item.endAge);
    });
    const list = conditionList.filter((p) => p.conditionType == currentConditionRow.conditionType);
    list[0].conditionValue = datas.join(',');
    list[0].conditionValueLabel = datas.join(',');
    list[0].meetWith = true;
  }
  showBacConditionAgeRef.value = false;
}

function addItemRules(result) {
  formData.otherItem = result;
  showBacItemDialog.value = false;
}

function closeItemRules() {
  showBacItemDialog.value = false;
}

function openOtherItem() {
  showBacItemDialog.value = true;
  proxy.$nextTick(() => {
    refBacIntelligentItem.value?.initPage(formData.otherItem);
  });
}

function openAntibiotic() {
  showBacAntibioticDialog.value = true;
  proxy.$nextTick(() => {
    refBacIntelligentAntibiotic.value?.initPage(formData.antibioticRule);
  });
}

function addAntibioticRules(result) {
  formData.antibioticRule = result;
  showBacAntibioticDialog.value = false;
}
function closeAntibioticRules() {
  showBacAntibioticDialog.value = false;
}

function confirmDialog() {
  showDataSelectDialog.value = false;
  let names: any = dialogForm.useDataList.map((m) => m.name);
  let codes: any = dialogForm.useDataList.map((m) => m.code);
  const list = conditionList.filter((p) => p.conditionType == currentConditionRow.conditionType);
  list[0].conditionValue = codes.join(',');
  list[0].conditionValueLabel = names.join(',');
  list[0].meetWith = dialogForm.condition == 1 ? true : false;
}

function addUseDataList({ row }) {
  dialogForm.dataList.splice(row, 1);
  dialogForm.useDataList.push(row);
}

function cancleUseDataList({ row }) {
  dialogForm.useDataList.splice(row, 1);
  dialogForm.dataList.push(row);
}

async function showDataDialog({ row }) {
  Object.assign(currentConditionRow, row);
  //从词典获取所有的病人类型
  if (row.conditionType != '3') {
    dialogForm.dataList.length = 0;
    dialogForm.useDataList.length = 0;
    let dataList = [];
    let url = '';
    switch (row.conditionType?.toString()) {
      case '1':
        url = '/api/sys/basDictDetail/findDictDetailList';
        await proxy.$http.get(url, { params: { code: 'PATTYPE' } }).then((res: any) => {
          dataList.push(...res.data);
        });
        break;
      case '2':
        url = '/api/sys/basDictDetail/findDictDetailList';
        await proxy.$http.get(url, { params: { code: 'sex' } }).then((res: any) => {
          dataList.push(...res.data);
        });
        break;
      case '3':
        break;
      case '4':
        url = '/api/sys/findDepartmentListbyCurrentUserOrg';
        await proxy.$http.get(url).then((res: any) => {
          dataList.push(...res.data);
        });
        break;
      case '5':
        url = '/api/sys/findDepartmentList';
        await proxy.$http.get(url).then((res: any) => {
          dataList.push(...res.data.deptList);
        });
        break;
      case '6':
        url = '/api/lab/labSampleType/findSampleTypeList';
        await proxy.$http.get(url, { params: { code: 'germType' } }).then((res: any) => {
          res.data.forEach((element) => {
            element.name = element.sampleTypeName;
            element.code = element.sampleTypeCode;
          });
          dataList.push(...res.data);
        });
        break;
      case '8':
        url = '/api/sys/basDictDetail/findDictDetailList';
        await proxy.$http.get(url, { params: { code: 'resistantType' } }).then((res: any) => {
          dataList.push(...res.data);
        });
        break;
      case '11':
        url = '/api/sys/basDictDetail/findDictDetailList';
        await proxy.$http.get(url, { params: { code: 'familyCode' } }).then((res: any) => {
          dataList.push(...res.data);
        });
        break;
      case '12':
        url = '/api/sys/basDictDetail/findDictDetailList';
        await proxy.$http.get(url, { params: { code: 'genusCode' } }).then((res: any) => {
          dataList.push(...res.data);
        });
        break;
      case '13':
        url = '/bac/germ/dict/getGermsByParams';
        await proxy.$http.get(url).then((res: any) => {
          res.data.forEach((element) => {
            element.name = element.germNa;
            element.code = element.germNo;
          });
          dataList.push(...res.data);
        });
        break;
      case '15':
        url = '/api/bac/bacReqPurpose/findPurposeList';
        await proxy.$http.get(url).then((res: any) => {
          res.data.forEach((element) => {
            element.name = element.purposeName;
            element.code = element.purposeNo;
          });
          dataList.push(...res.data);
        });
        break;
    }
    if (row.conditionValue) {
      const datas = row.conditionValue.split(',');
      dialogForm.dataList = dataList.filter((p) => !datas.includes(p.code));
      dialogForm.useDataList = dataList.filter((p) => datas.includes(p.code));
    } else {
      dialogForm.dataList = dataList;
    }
    dialogForm.condition = row.meetWith ? 1 : 2;
    dialogTitle = row.conditionName;
    showDataSelectDialog.value = true;
  } else {
    BacConditionAgeList.length = 0;
    if (row.conditionValue) {
      let datas = row.conditionValue.split(',');
      datas.forEach((element) => {
        const data = {
          startAge: element.split('-')[0],
          endAge: element.split('-')[1]
        };
        BacConditionAgeList.push(data);
      });
    }
    dialogTitle = row.conditionName;
    showBacConditionAgeRef.value = true;
  }
}

/**数据类型显示文本 */
function formatCommon(arr, value) {
  for (const item of arr) {
    if (item.value == value) {
      return item.name;
    }
  }
}

function saveAllBacRule() {
  currentRow.conditionList = conditionList;
  currentRow.operatList = operatList;
  currentRow.antibioticRule = formData.antibioticRule;
  currentRow.otherItem = formData.antibioticRule;

  let url = '/bac/rule/addAllBacRule';
  proxy.$http
    .post(url, currentRow)
    .then((res: any) => {
      proxy.$emit('findList', currentRow);
      VxeMessage('添加成功', VxeNotifyType.success);
    })
    .catch((err: any) => {});
}

// 新增
async function addOperat() {
  (proxy.$refs.OperatTableRef as any).clearCurrentRow();
  const row = {
    id: '',
    effect: '',
    operatRule: '',
    operatContent: ''
  };
  operatList.push(row);
  await OperatTableRef.value?.setCurrentRow(row);
}

async function deleteOperat() {
  const arr = (proxy.$refs.OperatTableRef as any).getCurrentRecord();
  operatList.splice(arr, 1);
}

// 获取规则
function getRowList(row) {
  Object.assign(currentRow, row);
  formData.otherItem = currentRow.otherItem;
  formData.antibioticRule = currentRow.antibioticRule;
  conditionList.length = 0; //放入数据前清空数据
  operatList.length = 0;
  const url = '/bac/rule/findBacRuleDetialList';
  proxy.$http
    //注意此处的数据条数
    .get(url, { params: row })
    .then(async (res: any) => {
      conditionList.push(...res.data.conditionList);
      operatList.push(...res.data.operatList);
    })
    .catch((err: any) => {
      VxeMessage('获取规则数据异常', VxeNotifyType.error);
    });
}

//**判断为空*/
function IsEmpty(value: any) {
  if (value === undefined || value === '' || value === null) {
    return true;
  }
  if (JSON.stringify(value) === '{}') {
    return true;
  }
  return false;
}

function getMediumName(row, event) {
  row.culMediumNo = event.value;
  const medium = sourcelist.find((item) => item.code === event.value);
  row.cultrueName = medium.name;
}
</script>

<style lang="scss" scoped>
#BacIntelligentExpertRuleForm {
  height: 100%;
  width: 100%;
  .area {
    height: 100%;
    .el-form {
      padding: 15px;
    }
    .detailsBtns {
      margin: 10px;
    }
  }
}
</style>
